package com.life.ai.server.framework.mybatis.handler;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.life.ai.server.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MyMetaObjectHandler
 *
 * @author kylewka
 * @since 2023/6/20
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_BY   = "createBy";    // 创建人
    public static final String CREATE_TIME = "createTime";  // 创建时间

    public static final String UPDATE_BY   = "updateBy";    // 更新人
    public static final String UPDATE_TIME = "updateTime";  // 更新时间

    /**
     * 插入时字段填充
     *
     * @param metaObject 原对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            // 创建时间与更新时间填充
            Object originalObject = metaObject.getOriginalObject();
            Date current = new Date();
            if (ReflectUtil.hasField(originalObject.getClass(), CREATE_TIME)) {
                Date createTime = (Date) metaObject.getValue(CREATE_TIME);
                current = ObjectUtil.isNotNull(createTime) ? createTime : current;
            }
            this.setFieldValByName(CREATE_TIME, current, metaObject);
            this.setFieldValByName(UPDATE_TIME, current, metaObject);

            // 创建人与更新人填充
            Long userId = getLoginUserId();
            if (ReflectUtil.hasField(originalObject.getClass(), CREATE_BY)) {
                Long createBy = (Long) metaObject.getValue(CREATE_BY);
                userId = ObjectUtil.isNotNull(createBy) ? createBy : userId;
            }
            if (ObjectUtil.isNotNull(userId)) {
                // 当前已登录 且 创建人为空 则填充
                this.setFieldValByName(CREATE_BY, userId, metaObject);
                // 当前已登录 且 更新人为空 则填充
                this.setFieldValByName(UPDATE_BY, userId, metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage());
        }
    }

    /**
     * 更新时字段填充
     *
     * @param metaObject 原对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            // 更新时间填充(不管为不为空)
            Date current = new Date();
            this.setFieldValByName(UPDATE_TIME, current, metaObject);
            // 当前已登录 更新人填充(不管为不为空)
            Long userId = getLoginUserId();
            if (ObjectUtil.isNotNull(userId)) {
                this.setFieldValByName(UPDATE_BY, userId, metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage());
        }
    }

    /**
     * 获取登录用户名
     */
    private Long getLoginUserId() {
        Long loginUserId = null;
        try {
            loginUserId = StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUserId;
    }
}
